using Game.Networking.Server;
using UnityEngine;

namespace Game {
	public sealed class ShipSignalReceiver : ISignalReceiver {
		const float EnergyToSendSignal = 500;

		public uint LastReceivedSignalId = 0;

		ShipCore _owner;

		public ShipSignalReceiver(ShipCore owner) {
			_owner= owner;
		}

		public bool HasNewSingals() {
			var b = ServerGameController.Instance.GetBaseForTeam(_owner.Team);
			if ( !GameManager.Instance.IsServer || b == null ) {
				return false;
			}
			return b.LastSignalId() > LastReceivedSignalId;
		}

		public ShipSignal GetSignal() {
			if ( !HasNewSingals() ) {
				return default;
			}
			var b = ServerGameController.Instance.GetBaseForTeam(_owner.Team);
			if ( b == null ) {
				return default;
			}
			var signal = b.ReadSignal(LastReceivedSignalId);
			if ( signal.SignalID >LastReceivedSignalId ) {
				LastReceivedSignalId= signal.SignalID;
			}
			if ( signal.CallerId == _owner.ID ) {
				return default;
			}
			return signal;
		}

		public bool SendSignal(ShipSignalType type, Vector3 point) {
			if ( !GameManager.Instance.IsServer || !_owner.Reactor.HasEnergy(EnergyToSendSignal)) {
				return false;
			}
			
			var b = ServerGameController.Instance.GetBaseForTeam(_owner.Team);
			if ( b == null ) {
				return false;
			}
			_owner.Reactor.UseEnergy(EnergyToSendSignal);
			b.SendSignal(_owner.ID, type, point);
			return true;
		}
	}
}
